package com.zryc.shop.filter;

import com.zryc.shop.jwt.JWTUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "auth-filter")
public class AuthGlobalFilterImpl implements GlobalFilter, Ordered {

    public List<String> getExcludes() {
        return excludes;
    }

    public void setExcludes(List<String> excludes) {
        this.excludes = excludes;
    }

    private List<String> excludes=new ArrayList<>();

    private final String AUTHORIZATION = "Authorization";//请求头中用于封装token的属性名

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //http://localhost:7001/service-product/product/1 错误401
        //http://localhost:7001/service-product/product/1?token=cjw 正确

        String uri = exchange.getRequest().getURI().getPath();//    获取本次请求的uri
        if (excludes.contains(uri)) {//判断本次请求的uri是否在排除列表中
            return chain.filter(exchange);//如果在，则直接进行下一个过滤器工作
        }
        //获取请求参数
        String token = exchange.getRequest().getHeaders().getFirst(AUTHORIZATION);//获取请求头中的token信息
        if (StringUtils.isEmpty(token)|| JWTUtil.parse(token.split(" ")[1])==null) {
            //不满足身份验证，给一个未认证的code
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //请求结束
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 指定过滤器的执行顺序，返回-1表示这个过滤器执行序列较高，会在前执行
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
